import { defaHttp } from "@@/api/index";
import { notify } from "@@/hooks/vantHooks";
import { CinputImage } from "@@/components/common/CinputImages/index";
import { imageCompress } from "@@/utils/tools/file";
import { i18n } from "@@/language";

export async function aipUploadImages(data: FormData): Promise<UploadImage.Res> {
  const res: any = await defaHttp.axios({
    url: "/upload",
    method: "POST",
    headers: {
      "Content-Type": "multipart/form-data",
    },
    data,
  });
  return res;
}
export const UPLOAD_FILE_MAX = 1024 * 1024 * 2;
export namespace UploadImage {
  export interface Res {
    errno: number;
    data: {
      urls: string[];
      paths: string[];
    };
  }
}
//@ts-ignore
const { t } = i18n.global;

export async function uploadImages(images: CinputImage[]) {
  if (!images.length) return "";
  notify.primary(t("zhen-zai-ya-suo-tu-pian"), {
    duration: 0,
  });
  const formData = new FormData();
  for (const img of images) {
    let file = img.file;
    if (file.size > UPLOAD_FILE_MAX)
      file = await imageCompress(file, UPLOAD_FILE_MAX);
    formData.append(file.name, file);
  }
  notify.primary(t("zhen-zai-shang-chuan-tu-pian"), {
    duration: 0,
  });
  const res = await aipUploadImages(formData);
  if (res.errno !== 0) {
    notify.error(t("shang-chuan-shi-bai"));
    return Promise.reject();
  }
  notify.success(t("shang-chuan-cheng-gong"));
  return res.data.paths.join(",");
}
